import axios from 'axios'
import store from '@/store'
import { Toast, Dialog } from 'vant'
import router from '@/router'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
import { getISOTime, getAuthorization } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000, // request timeout
  transformRequest: [
    function (data) {
      // if (data) { debugger }
      return JSON.stringify(data)
    }
  ]
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    if (store.getters.token) {
      const date = new Date()
      config.headers['x-wp-date'] = getISOTime(date)
      config.headers['authorization'] = getAuthorization(date)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    console.log(response)
    if (res.code === 0) {
      return Promise.resolve(res)
    } else if (res.code === -2) {
      Toast({
        message: res.msg || `请求失败`
      })
    } else if (res.code === 600) {
      Toast({
        message: res.msg || `请求失败`
      })
    } else if (res.code >= 10000 && res.code <= 10099) {
      // console.log(`鉴权code = ${res.code}`)
      Dialog.confirm({
        title: '系统提示',
        message: res.msg
      }).then(() => {
        router.push('/login')
      })
      return Promise.reject(res)
    } else if (res.code >= 10000) {
      Toast({
        message: res.msg || `请求失败`
      })
    } else {
      return Promise.reject(res)
    }
    return Promise.reject('请求错误')
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
